//
//  UIImage+ERCustomAlert.m
//  EnjoyRunning
//
//  Created by ljm on 2017/4/24.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "UIImage+ERCustomAlert.h"
#import <Accelerate/Accelerate.h>

@implementation UIImage (ERCustomAlert)

#pragma mark -- 获取屏幕截图图像
+ (UIImage *)getScreenShot
{
    /*
     *    获取窗口
     */
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    /*
     *    开始上下文
     */
    UIGraphicsBeginImageContextWithOptions(window.bounds.size, YES, 0);
    
    /*
     *    将获取到的window内容绘制到输出的当前上下文
     */
    [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
    
    /*
     *    获取原图片
     */
    UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
    
    /*
     *    关闭上下文
     */
    UIGraphicsEndImageContext();
    
    return screenShotImage;
}

#pragma mark -- 处理原图片，使模糊
+ (UIImage *)blurredWithImage:(UIImage *)originalImage blured:(CGFloat)blured
{
    /*
     *    处理模糊越界
     */
    if (blured < 0.f || blured > 1.f) {
        blured = 0.5f;
    }
    int rangeSize = blured * 40;
    rangeSize = rangeSize - (rangeSize % 2) + 1;
    
    /*
     *    创建像素图对象
     */
    CGImageRef image = originalImage.CGImage;
    
    vImage_Buffer inbuffer , outbuffer;
    vImage_Error error;
    
    void *pixerBuffer;
    
    /*
     *    获取图像数据
     */
    CFDataRef inBitMapData = CGDataProviderCopyData(CGImageGetDataProvider(image));
    
    /*
     *    设置获取到的图像属性
     */
    inbuffer.width = CGImageGetWidth(image);
    inbuffer.height = CGImageGetHeight(image);
    inbuffer.rowBytes = CGImageGetBytesPerRow(image);
    
    inbuffer.data = (void *)CFDataGetBytePtr(inBitMapData);
    
    pixerBuffer = malloc(CGImageGetBytesPerRow(image) * CGImageGetHeight(image));
    
    if (pixerBuffer == NULL) {
        NSLog(@"!!!!!!!!!!=====no pixerBuffer======!!!!!!!!!!!");
    }

    outbuffer.data = pixerBuffer;
    outbuffer.width = CGImageGetWidth(image);
    outbuffer.height = CGImageGetHeight(image);
    outbuffer.rowBytes = CGImageGetBytesPerRow(image);
    
    error = vImageBoxConvolve_ARGB8888(&inbuffer, &outbuffer, NULL, 0, 0, rangeSize, rangeSize, NULL, kvImageEdgeExtend);
    
    if (error) {
        NSLog(@"!!!!!!!!!!!!!!!!!!!!!!!!!\nerror from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef contextRef = CGBitmapContextCreate(
                                                    outbuffer.data, outbuffer.width, outbuffer.height, 8, outbuffer.rowBytes, colorSpace, kCGImageAlphaNoneSkipLast);
   
    CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    CGContextRelease(contextRef);
    CGColorSpaceRelease(colorSpace);
    
    free(pixerBuffer);
    CFRelease(inBitMapData);
    
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    
    return returnImage;
}

@end
